// ==UserScript==
// @name        剧集记录脚本
// @namespace   Violentmonkey Scripts
// @match       https://v.qq.com/*
// @match       https://www.bilibili.com/*
// @grant       GM_setValue
// @grant       GM_getValue
// @grant       GM_addStyle
// @version     1.4
// @author      小菜鸟爱学习
// @description 2023/4/14 11:23:22
// ==/UserScript==
(function () {
  'use strict';
  // console.log('我是脚本')

  const href = window.document.location.href

  let WEB_SITE
  if (href.indexOf('v.qq.com') >= 0) {
    WEB_SITE = 'tencent'
  } else if (href.indexOf('www.bilibili.com') >= 0) {
    WEB_SITE = 'bilibili'
  }

  console.log('WEB_SITE', WEB_SITE)


  const data = {
    title: undefined,
    episode: undefined,
    storedEpisode: undefined
  }
  window.onload = () => {
    // console.log('page loaded')
    pageLoad()
  }

  let showTip;
  const showInfo = () => {
    // console.log(`当前：${data.episode}，已看：${data.storedEpisode===undefined?'无':data.storedEpisode}。`)
    if (!showTip) {
      showTip = document.createElement('div')
      showTip.setAttribute('id', 'myShowTip')
      document.body.appendChild(showTip)
      GM_addStyle('#myShowTip{background: rgba(255,0,0,0.3);position: fixed;top: 0;left: 0;z-index: 9999;border-radius: 5px;font-size: 24px;color: #fff;padding-left: 14px;}')

      // document.getElementsByClassName('intro-wrapper__title')[0].appendChild(showTip)
      // GM_addStyle('#myShowTip{background: rgba(255,0,0,0.3);border-radius: 5px;font-size: 14px;color: #fff;padding-left: 14px;}')
    }

    showTip.innerText = `当前：${data.episode}，已看：${data.storedEpisode === undefined ? '无' : data.storedEpisode}。`

  }

  const getStoredData = () => {
    const storedEpisode = GM_getValue(data.title)
    if (!!storedEpisode) {
      data.storedEpisode = parseInt(storedEpisode)
    }
  }

  let timer
  const refreshData = () => {
    !!timer && clearTimeout(timer)

    showInfo()

    // 五分钟观看时长则记录当前集数
    timer = setTimeout(() => {
      GM_setValue(data.title, data.episode)
      data.storedEpisode = data.episode

      showInfo()
    }, 5 * 60 * 1000)

    // if (data.storedEpisode === undefined || data.storedEpisode < data.episode) {
    //   GM_setValue(data.title, data.episode)
    //   data.storedEpisode = data.episode
    // }
  }

  // 按钮换集监听
  const addListener = () => {

    // 按钮跳转的无需监听

    if (WEB_SITE === 'tencent') {
      const addClickListener = () => {
        const epBtns = document.querySelectorAll('.episode-item.episode-item-rect.episode-item-rect--number')
        // console.log("epBtns", epBtns)
        if (epBtns.length) {
          for (let i = 0; i < epBtns.length; i++) {
            epBtns[i].onclick = (e) => {
              // console.log('click', e.target.innerText)
              data.episode = e.target.innerText
              refreshData()
            }
          }
        }
      }
      addClickListener()

      // 1-100 101-200 按钮
      const epTabBtns = document.querySelectorAll('.b-tab__item')
      if (epTabBtns.length) {
        for (let i = 0; i < epTabBtns.length; i++) {
          epTabBtns[i].onclick = (e) => {
            setTimeout(() => {
              addClickListener()
            }, 500)
          }
        }
      }
    } else if (WEB_SITE === 'bilibili') {
      const addClickListener = () => {
        const epBtns = document.querySelector('#danmukuBox').nextSibling.lastChild.children
        // console.log("epBtns", epBtns)
        if (epBtns.length) {
          for (let i = 0; i < epBtns.length; i++) {
            epBtns[i].onclick = (e) => {
              // console.log('click', e.target.innerText)
              data.episode = e.target.innerText
              refreshData()
            }
          }
        }
      }
      addClickListener()

      // 列表，方块展示切换按钮
      const epTabBtn = document.querySelector('#danmukuBox').nextSibling.firstChild.firstChild.lastChild
      epTabBtn.onclick = (e) => {
        setTimeout(() => {
          addClickListener()
        }, 500)
      }

    }
  }

  const getTitleElement = () => {
    if (WEB_SITE === 'tencent') {
      return document.querySelector('.intro-wrapper__title')
    } else if (WEB_SITE === 'bilibili') {
      const tempArray = []
      document.querySelector(".player-left-components").children.forEach(c => tempArray.push(c))
      const div1 = tempArray.filter(c => c.className && c.className.includes('mediainfo_'))[0]
      return div1.querySelector('div').querySelector('a')
    }
  }

  const findTitle = () => {
    let title
    const titleDom = getTitleElement()
    // console.log('titleDom', titleDom)
    if (!!titleDom) {
      title = titleDom.innerText
    }
    return title
  }

  const findCurrentEpisode = () => {
    let currentEpisode
    if (WEB_SITE === 'tencent') {
      currentEpisode = document.querySelector('.episode-item.episode-item-rect.episode-item--active.episode-item-rect--number>span').innerText
    } else if (WEB_SITE === 'bilibili') {
      const tempArray = []
      document.querySelector('#danmukuBox').nextSibling.lastChild.children.forEach(c => tempArray.push(c))
      currentEpisode = tempArray.filter(c => c.className && c.className.includes('_select_'))[0].title
    }
    return currentEpisode
  }

  const pageLoad = () => {
    const title = findTitle()
    console.log('title', title)
    if (title) {
      data.title = title
      const currentEpisode = findCurrentEpisode()
      console.log('currentEpisode', currentEpisode)
      if (currentEpisode) {
        data.episode = currentEpisode
      }
    }
    if (data.title && !!data.episode) {
      getStoredData()
      refreshData()
      addListener()
    }
  }
})();